package dados;

import excessoes.ClienteInexistenteException;
import negocio.Cliente;

import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class RepClienteHibernate implements RepCliente{
	
	//Atributo Session do hibernate
	private Session session;

	private Session getSession() throws SQLException{
		if(session==null || !session.isOpen()){
			session = HibernateConnection.getSession();
		}		
		return session;
	}
	
	/*
	 * metodos inserir, remover, atualizar, existe e procurar. Todos sobrescritos do repcliente(non-Javadoc)
	 * metodo vector?????????????????????/
	 */
	@Override
	public void inserir(Cliente c) {
		try{
			session = getSession();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		Transaction t =session.beginTransaction();
		
		session.save(c);
		
		t.commit();
		session.flush();
	}
	
	@Override
	public void remover(String cpf) throws ClienteInexistenteException {
		try{
			session = getSession();
		}catch (Exception e) {
			e.printStackTrace();
		}
		Cliente cliente = procurar(cpf);
		
		Transaction t =session.beginTransaction();
		
		session.delete(cliente);
		
		t.commit();
		session.flush();
	}
	
	@Override
	public void atualizar(Cliente c) throws ClienteInexistenteException {
		Transaction t = session.beginTransaction();
		
		session.saveOrUpdate(c);
		
		t.commit();
		session.flush();
	}
	
	@Override
	public boolean existe(String cpf) {
		boolean existe = true;
		try {
			procurar(cpf);
		} catch (Exception e) {
			existe = false;
		}
		return existe;
	}
	
	@Override
	public Cliente procurar(String cpf) throws ClienteInexistenteException{
		try{
			Session session = getSession();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		Cliente retorno = (Cliente) session.get(Cliente.class,cpf);
		if(retorno == null){
			throw new ClienteInexistenteException(cpf);
		}
		return retorno;
	}
	
	public Vector<Cliente> listar() {
		try{
			Session session = getSession();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		Query q =  session.getNamedQuery("cliente.listar");
		
		@SuppressWarnings("unchecked")
		List<Cliente> clientes = q.list();

		Vector<Cliente> retorno = new Vector<Cliente>(clientes.size(),1);
		
		for(Cliente c : clientes){
			retorno.add(c);
		}
		
		return retorno;
	}
}
